<template>
    <div>
        <!-- 头部导航 -->
        <div class="nav">
            <div class="container">
                <!-- 左侧 -->
                <ul>
                    <li @click="$router.push('/')">
                        <!-- 朋友圈 -->
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-QQkongjian"></use>
                        </svg>
                        <span class="title">朋友圈</span>
                    </li>
                    <li @click="$router.push('/')">
                        <!-- 个人中心 -->
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-yonghu"></use>
                        </svg>
                        <span>个人中心</span>
                    </li>
                    <!-- 我的主页 -->
                    <!-- <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-zhuye"></use>
                        </svg>
                        <span>我的主页</span>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-shixiangxiajiantou--copy"></use>
                        </svg>
                    </li> -->
                    <li class="friend-menu-item" @mouseenter="showFriendDropdown = true"
                        @mouseleave="showFriendDropdown = false">
                        <!-- 好友 -->
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-haoyou"></use>
                        </svg>
                        <span>好友</span>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-shixiangxiajiantou--copy"></use>
                        </svg>

                        <!-- 好友下拉菜单 -->
                        <div class="friend-dropdown" v-show="showFriendDropdown" @mouseenter="showFriendDropdown = true"
                            @mouseleave="showFriendDropdown = false">
                            <div class="search-box">
                                <input type="text" v-model="friendSearch" placeholder="搜索好友" @click.stop>
                                <svg class="search-icon" aria-hidden="true">
                                    <use xlink:href="#icon-sousuo"></use>
                                </svg>
                            </div>
                            <div class="friend-list">
                                <div class="friend-item" v-for="friend in filteredFriends" :key="friend.id"
                                    @click="goToFriendSpace(friend.id)">
                                    <img :src="friend.avatar" class="friend-avatar">
                                    <span class="friend-name">{{ friend.name }}</span>
                                </div>
                                <div class="no-friends" v-if="filteredFriends.length === 0">
                                    暂无好友
                                </div>
                            </div>
                        </div>
                    </li>
                    <!-- 游戏 -->
                    <!-- <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-houtaishangpinguanli-copy"></use>
                        </svg>
                        <span>游戏</span>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-shixiangxiajiantou--copy"></use>
                        </svg>
                    </li> -->
                    <!-- 装扮 -->
                    <!-- <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-clothes-copy"></use>
                        </svg>
                        <span>装扮</span>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-shixiangxiajiantou--copy"></use>
                        </svg>
                    </li> -->
                </ul>
                <!-- 右侧 -->
                <ul>
                    <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-zhongzhi"></use>
                        </svg>
                    </li>
                    <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-format-horizontal-align-bottom"></use>
                        </svg>
                    </li>
                    <!-- <li>
                        <div class="search-input">
                            <p>用户/游戏/动态</p>
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-sousuo"></use>
                            </svg>
                        </div>
                    </li> -->
                    <li @click="router.push('/personal-center')">
                        <img class="avatar" :src="info.avatar_url" alt="">
                        <span>{{ info.name }}</span>
                    </li>
                    <li>
                        <!-- 退出登录 -->
                        <svg class="icon" aria-hidden="true" @click="logout">
                            <use xlink:href="#icon-tuichu"></use>
                        </svg>
                    </li>
                    <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-shezhi-copy"></use>
                        </svg>
                    </li>
                    <li>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-huangzuan"></use>
                        </svg>
                    </li>
                </ul>
                <svg class="xinhaotiao" aria-hidden="true">
                    <use xlink:href="#icon-xinhaotiao"></use>
                </svg>
            </div>
        </div>
        <div class="sky" v-if="!friendInfo">
            <div class="container">
                <div class="title">{{ info.name }}的空间</div>
                <div class="info">
                    <img class="avatar" :src="info.avatar_url" alt="">
                    <span class="name">{{ info.name }}</span>
                    <!-- <img class="huangzuan" src="../../assets/img/开通黄钻.png" alt=""> -->
                </div>
            </div>
        </div>
        <div class="sky" v-else>
            <div class="container">
                <div class="title">{{ friendInfo.name }}的空间</div>
                <div class="info">
                    <img class="avatar" :src="friendInfo.avatar_url" alt="">
                    <span class="name">{{ friendInfo.name }}</span>
                    <!-- <img class="huangzuan" src="../../assets/img/开通黄钻.png" alt=""> -->
                </div>
            </div>
        </div>
        <!-- {{ friendShow }} -->
        <div class="menu" v-if="friendShow">
            <div class="container">
                <ul class="menu-list">
                    <li @click="$router.push('/main')">主页</li>
                    <li @click="$router.push('/shuoshuo')">发布说说</li>
                    <li @click="$router.push('/personal-center')">个人信息</li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, computed, watch, onUnmounted } from 'vue'
import api from '../../api/index'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { emitter } from '@/utils/eventBus';


const route = useRoute()

const router = useRouter()
const store = useStore()
// 个人信息
const info = ref({})

const showFriendDropdown = ref(false)
const friendSearch = ref('')
const friends = ref([])

// 获取好友列表
const fetchFriends = async () => {
    try {
        const res = await api.getFriendList({ userid: store.state.userid })
        if (res.code === 200) {
            // 根据每个好友的id获取好友信息
            const friendInfo = await Promise.all(res.data.map(async (friend) => {
                const friendRes = await api.getUserInfo({ userid: friend.id })
                if (friendRes.code === 200) {
                    return friendRes.data[0]
                }
            }))
            res.data.forEach((friend, index) => {
                friend.avatar = friendInfo[index].avatar_url
                friend.name = friendInfo[index].name
            })

            friends.value = res.data;
        }
    } catch (error) {
        console.error('获取好友列表失败:', error)
    }
}

// 过滤好友列表
const filteredFriends = computed(() => {
    if (!friendSearch.value) return friends.value
    return friends.value.filter(friend =>
        friend.name.toLowerCase().includes(friendSearch.value.toLowerCase())
    )
})

// 跳转到好友空间
const goToFriendSpace = (friendId) => {
    router.push(`/main?friendId=${friendId}`)
    showFriendDropdown.value = false
}

// 点击外部关闭下拉菜单（保留原有逻辑）
const closeDropdownOnClickOutside = (e) => {
    if (!e.target.closest('.friend-menu-item') && !e.target.closest('.friend-dropdown')) {
        showFriendDropdown.value = false
    }
}

// 点击好友菜单项时切换显示状态
const toggleFriendDropdown = () => {
    showFriendDropdown.value = !showFriendDropdown.value
}

// 显示或隐藏菜单
const friendShow = computed(() => !route.query.friendId);

const friendInfo = ref(null);

watch(
    () => route.query.friendId,
    async (friendId) => {
        if (friendId) {
            const res = await api.getUserInfo({ userid: friendId });
            if (res.code === 200) {
                friendInfo.value = res.data[0];
            }
        } else {
            friendInfo.value = null;
        }
    },
    { immediate: true }
);

// 获取用户信息
const refreshUserInfo = () => {
    api.getUserInfo({ userid: store.state.userid }).then(res => {
        if (res.code === 200) {
            info.value = res.data[0];
        }
    });
};

onMounted(() => {
    // 获取用户信息
    refreshUserInfo();
    emitter.on('refresh-user-info', refreshUserInfo);

    fetchFriends()
    document.addEventListener('click', closeDropdownOnClickOutside)

});

onUnmounted(() => {
    emitter.off('refresh-user-info');
});

// 退出登录
const logout = () => {
    store.dispatch('logout')
    router.push('/login')
}
</script>

<style lang="less" scoped>
// 头部导航
.nav {
    height: 41px;
    background-color: #1f1f1f;
    color: white;

    .container {
        margin: 0 auto;
        height: 41px;
        width: 1100px;
        display: flex;
        justify-content: space-between;
        // background-color: red;

        .title {
            font-weight: bold;
        }

        ul {
            height: 100%;
            cursor: pointer;
        }


        li {
            float: left;
            height: 100%;
            margin: 0 8px;
            display: flex;
            align-items: center;
        }

        li:nth-child(n+2) span {
            margin: 0 5px;
            font-size: 12px;
        }

        li .icon {
            width: 20px;
            height: 20px;
        }

        ul:first-child li:first-child .icon {
            width: 30px;
            height: 30px;
        }

        .search-input {
            background-color: #575757;
            color: #cfcfcf;
            font-size: 12px;
            width: 120px;
            height: 20px;
            line-height: 20px;
            display: flex;
            justify-content: space-between;
        }

        .avatar {
            height: 25px;
        }
    }

    .xinhaotiao {
        height: 15px;
        width: 15px;
        position: absolute;
        top: 12px;
        right: 10px;
    }
}

.sky {
    height: 350px;
    // background-color: red;
    background: url(../../assets/img/sky.png) no-repeat;
    background-size: cover;

    .container {
        margin: 0 auto;
        width: 1100px;
        // background-color: red;
        height: 350px;
        overflow: hidden;
        position: relative;

        .title {
            color: white;
            font-weight: bold;
            font-size: 30px;
            margin: 30px 0;
        }

        .info {
            position: absolute;
            bottom: 0px;
            left: 0;
            display: flex;

            .avatar {
                height: 150px;
                width: 150px;
            }

            .name {
                color: white;
                font-size: 24px;
                margin-left: 20px;
                margin-top: 80px;
            }

            .huangzuan {
                width: 153px;
                height: 39px;
                margin-left: 10px;
                margin-top: 75px;
            }

        }


    }
}

// 菜单导航
.menu {
    height: 50px;
    background-color: #fafafa;

    .container {
        margin: 0 auto;
        width: 1100px;
        height: 50px;

        .menu-list {
            height: 100%;
            display: flex;
            align-items: center;

            li {
                margin: 0 20px;
            }

            li:hover {
                text-decoration: underline;
                cursor: pointer;
            }
        }
    }
}

.friend-menu-item {
    position: relative;

    &:hover {
        background-color: rgba(255, 255, 255, 0.1);
    }
}

.friend-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    width: 240px;
    /* 固定下拉菜单宽度 */
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    padding: 12px;
    border: 1px solid #eaeaea;
    min-width: 240px; // 添加最小宽度
    box-sizing: border-box; // 重要！

    .search-box {
        position: relative;
        margin-bottom: 12px;
        width: 100%;
        /* 确保搜索框不超出父容器 */

        input {
            width: 100%; // 改为100%宽度
            box-sizing: border-box; // 添加盒模型计算
            padding: 8px 32px 8px 12px; // 保持原有padding
            /* 考虑搜索图标的空间 */
            border: 1px solid #ddd;
            border-radius: 20px;
            outline: none;
            font-size: 13px;
            background-color: #f5f5f5;

            &:focus {
                border-color: #4CAF50;
                background-color: #fff;
                box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
            }
        }

        .search-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            pointer-events: none; // 防止图标干扰输入
            width: 16px;
            height: 16px;
            color: #999;
        }
    }

    .friend-list {
        max-height: 300px;
        overflow-y: auto;

        .friend-item {
            display: flex;
            align-items: center;
            padding: 8px 0;
            /* 去除左右padding使内容靠左 */
            width: 100%;
            /* 确保宽度不超出 */

            &:hover {
                background-color: #f0f7ff;
            }

            .friend-avatar {
                width: 36px;
                height: 36px;
                margin-right: 10px;
            }

            .friend-name {
                font-size: 14px;
                color: #333;
                /* 修改文字颜色为深色 */
                font-weight: 500;
                flex: 1;
                /* 让名字占据剩余空间 */
                text-align: left;
                /* 确保文字左对齐 */
                white-space: nowrap;
                /* 防止文字换行 */
                overflow: hidden;
                text-overflow: ellipsis;
                /* 文字过长显示省略号 */
            }
        }

        .no-friends {
            padding: 12px;
            text-align: center;
            color: #999;
            font-size: 13px;
        }
    }

    /* 滚动条样式 */
    &::-webkit-scrollbar {
        width: 6px;
    }

    &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
    }
}
</style>